﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using YF_Music.Core.Models;

namespace YF_Music.Core.Converters
{
  public static class MusicItemConverter
  {
    private static readonly string ArtFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cache", "album_art");

    public static SerializableMusicItem ToSerializable(MusicItem item)
    {
      string imagePath = "";
      if (!item.IsDefaultImage)
      {
        imagePath = SaveAlbumArtToFile(item.AlbumArt, item.ID);
      }
      return new SerializableMusicItem
      {
        ID = item.ID,
        Title = item.Title,
        Author = item.Author,
        Album = item.Album,
        Duration = item.Duration,
        FileSize = item.FileSize,
        IsDefaultImage = item.IsDefaultImage,
        Format = item.Format,
        PlayCount = item.PlayCount,
        AddTime = item.AddTime,
        FilePath = item.FilePath,
        Downloaded = item.Downloaded,
        SoundQuality = item.SoundQuality,
        LyricPath = item.LyricPath,
        AlbumArtPath = imagePath
      };
    }

    public static MusicItem FromSerializable(SerializableMusicItem dto)
    {
      return new MusicItem
      {
        ID = dto.ID,
        Title = dto.Title,
        Author = dto.Author,
        Album = dto.Album,
        Duration = dto.Duration,
        FileSize = dto.FileSize,
        Format = dto.Format,
        IsDefaultImage = dto.IsDefaultImage,
        PlayCount = dto.PlayCount,
        AddTime = dto.AddTime,
        FilePath = dto.FilePath,
        Downloaded = dto.Downloaded,
        SoundQuality = dto.SoundQuality,
        LyricPath=dto.LyricPath,
        AlbumArt = LoadAlbumArtFromFile(dto.AlbumArtPath, dto.IsDefaultImage)
      };
    }

    private static string SaveAlbumArtToFile(ImageSource image, string id)
    {
      if (image is not BitmapSource bitmap) return null;

      Directory.CreateDirectory(ArtFolder);
      string path = Path.Combine(ArtFolder, $"{id}.png");

      var encoder = new PngBitmapEncoder();
      encoder.Frames.Add(BitmapFrame.Create(bitmap));

      using var fs = new FileStream(path, FileMode.Create);
      encoder.Save(fs);

      return path;
    }

    private static ImageSource LoadAlbumArtFromFile(string path, bool isDefaultImage)
    {
      if (isDefaultImage || path == "" || !File.Exists(path))
      {
        return MusicItem.LoadDefaultImage();
      }

      var bitmap = new BitmapImage();
      bitmap.BeginInit();
      bitmap.UriSource = new Uri(path, UriKind.Absolute);
      bitmap.CacheOption = BitmapCacheOption.OnLoad;
      bitmap.EndInit();
      bitmap.Freeze();
      return bitmap;
    }
  }
}
